#include <iostream>
using namespace std;

void print_storage_info(const int* next, const int *prev, int ints) {
  if (next) {
    cout << ((next != prev) ? "New" : "Old") 
         << " location: " << next
         << " ints: " << ints << " "
         << "(" << ints * sizeof(int) << ") bytes" << endl;
  } else {
    cout << "Allocation failed." << endl;
  }
}

int main() {
  const int pattern[] = { 1, 2, 3, 4, 5, 6, 7, 8 };
  const int pattern_size = sizeof(pattern)/sizeof(int);

  int *next = NULL;
  int *prev = NULL;
  
  next =(int *)malloc(pattern_size * sizeof(*next));
  if (next) {
    // 将 pattern[] 拷贝到 next 指向的内存
    memcpy(next, pattern, sizeof(pattern));
    print_storage_info(next, prev, pattern_size);
  } else {
    exit(1);
  }
  

  const int realloc_size[] = { 10, 12, 512, 32768, 65536, 32768 };
  const int realloc_size_len = sizeof(realloc_size) / sizeof(int);
  for (int i = 0; i < realloc_size_len; i++) {
    const int ints = realloc_size[i];
    prev = next;
    next = (int *)realloc(prev, ints * sizeof(int));
    if (next) {
      print_storage_info(next, prev, ints);
      assert(!memcmp(next, pattern, sizeof(pattern)));
    } else {
      free(prev);
      prev = NULL;
      exit(1);
    }
  }

  for(int i = 0; i < pattern_size; i++) {
    cout << next[i] << " " ;
  }
  cout << endl;

  free(next);
  return 0;
}
